<template>
  <div class="record-editor-view">
    <div class="editor-content">
      <div class="editor">
        <textarea v-model="recordData.text" placeholder="分享新鲜事..." class="editor-textarea"></textarea>
        <div class="editor-toolbar">
          <van-icon name="hashtag" class="toolbar-icon" />
          <van-icon name="photo" class="toolbar-icon" />
          <van-icon name="font" class="toolbar-icon" />
          <van-icon name="todo-list" class="toolbar-icon" />
          <span class="toolbar-divider"></span>
          <van-icon name="ellipsis" class="toolbar-icon" />
          <div class="toolbar-voice-picker">
            <span class="toolbar-voice-label" @click="showVoicePicker = true">{{ voiceLabel }}</span>
            <van-popup v-model:show="showVoicePicker" position="bottom">
              <van-picker
                :columns="voiceOptions"
                :default-index="voiceOptions.findIndex(o => o.value === voiceAction)"
                @confirm="onVoiceConfirm"
                @cancel="showVoicePicker = false"
                show-toolbar
              />
            </van-popup>
          </div>
        </div>
      </div>

      <!-- 生成候选卡片 -->
      <div
        v-if="showAICard"
        class="ai-gen-card"
      >
        <div class="ai-gen-card-header">
          <div class="ai-gen-title">AI生成 - {{ voiceLabel }}</div>
          <div class="ai-gen-actions">
            <van-button size="small" @click="regenerateCandidates" :loading="aiLoading">重新生成</van-button>
          </div>
        </div>

        <div class="ai-gen-body">
          <div v-if="aiLoading" class="ai-loading">
            <van-loading size="24px" />
            <span class="ai-loading-text">正在生成候选图...</span>
          </div>

          <div v-else class="ai-candidates">
            <div
              v-for="(url, idx) in aiCandidates"
              :key="url + idx"
              class="ai-candidate"
              :class="{ selected: selectedCandidate === idx }"
              @click="selectedCandidate = idx"
            >
              <img :src="url" alt="候选图片" />
              <div class="checkmark" v-if="selectedCandidate === idx">
                <svg viewBox="0 0 24 24" width="18" height="18">
                  <path d="M20 6L9 17l-5-5" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
        </div>

      </div>

      <div class="settings-section">
        <div class="settings-item">
          <span class="settings-label" @click="showPermissionPicker = true">权限设置</span>
          <span class="settings-value" @click="showPermissionPicker = true">{{ permissionLabel }}</span>
          <van-popup v-model:show="showPermissionPicker" position="bottom">
            <van-picker
              :columns="permissionOptions"
              :default-index="permissionOptions.findIndex(o => o.value === permissionAction)"
              @confirm="onPermissionConfirm"
              @cancel="showPermissionPicker = false"
              show-toolbar
            />
          </van-popup>
        </div>
        <span class="settings-divider-solid"></span>
        <div class="settings-item">
          <span class="settings-label" @click="showSchedulePicker = true">定时</span>
          <span class="settings-value" @click="showSchedulePicker = true">{{ scheduleLabel }}</span>
          <van-popup v-model:show="showSchedulePicker" position="bottom">
            <van-picker
              :columns="scheduleOptions"
              :default-index="scheduleOptions.findIndex(o => o.value === scheduleAction)"
              @confirm="onScheduleConfirm"
              @cancel="showSchedulePicker = false"
              show-toolbar
            />
          </van-popup>
        </div>
      </div>
    </div>

    <div class="editor-header">
      <van-button type="primary" @click="publishNote" class="publish-button">发布</van-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useNotesStore } from '@/stores/notes';

export default defineComponent({
  name: 'RecordEditorView',
  setup() {

    const router = useRouter();
    const notesStore = useNotesStore();
    const recordData = ref({
      text: '',
      photos: [] as UploaderFileListItem[],
    });

    // voice picker
    const voiceOptions = [
      { text: '生成图片', value: 'sticker' },
      { text: '生成贴纸', value: 'image' },
    ];
    const voiceAction = ref<'sticker' | 'image'>('sticker');
    const showVoicePicker = ref(false);
    const voiceLabel = computed(() => voiceOptions.find(o => o.value === voiceAction.value)?.text || '');

    // === AI候选生成相关 ===
    const showAICard = ref(false);
    const aiLoading = ref(false);
    const aiCandidates = ref<string[]>([]);
    const selectedCandidate = ref<number | null>(null);

    // 模拟生成两张候选图
    const generateCandidates = async () => {
      aiLoading.value = true;
      selectedCandidate.value = null;

      // 模拟调用后端生成接口，这里用占位图替代
      // 你可以换成实际的 fetch('/api/generate', { method:'POST', body:{ type: voiceAction.value, text: recordData.value.text } })
      await new Promise(r => setTimeout(r, 800));
      const tag = voiceAction.value === 'sticker' ? 'Sticker' : 'Image';
      aiCandidates.value = [
        `https://ku-sheet-server.baidu-int.com/uploader/f/1kQswgRHbKkIOzyo.png?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzgwOTgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNzQ5OCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.R4qUoZ07NOt6kKD8Yc1sHLB9EE9cP3z28RTsbm-28Bse`,
        `https://ku-sheet-server.baidu-int.com/uploader/f/3h8qgcQ7i1bvbWer.jpg?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzgwOTgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNzQ5OCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.R4qUoZ07NOt6kKD8Yc1sHLB9EE9cP3z28RTsbm-28Bs`,
      ];
      aiLoading.value = false;
    };

    const regenerateCandidates = () => {
      generateCandidates();
    };

    const useSelectedCandidate = () => {
      if (selectedCandidate.value == null) return;
      const url = aiCandidates.value[selectedCandidate.value];
      // 加入到当前记录的图片列表（Vant Uploader 兼容的对象）
      recordData.value.photos.unshift({ url } as any);
      // 也可以选择收起卡片：根据产品需要决定
      // showAICard.value = false;
    };

    // 选择确认后：展示卡片并生成
    const onVoiceConfirm = (value: any) => {
      const v = Array.isArray(value) ? value[0]?.value : value?.value;
      if (v === 'sticker' || v === 'image') {
        voiceAction.value = v;
      }
      showVoicePicker.value = false;
      showAICard.value = true;
      generateCandidates();
    };

    // permission picker
    const permissionOptions = [
      { text: '所有人可见', value: 'public' },
      { text: '仅好友可见', value: 'friends' },
      { text: '仅自己可见', value: 'private' },
    ];
    const permissionAction = ref('public');
    const showPermissionPicker = ref(false);
    const permissionLabel = computed(() => permissionOptions.find(o => o.value === permissionAction.value)?.text || '');
    const onPermissionConfirm = (value: any) => {
      const v = Array.isArray(value) ? value[0]?.value : value?.value;
      if (v) permissionAction.value = v;
      showPermissionPicker.value = false;
    };

    // schedule picker
    const scheduleOptions = [
      { text: '立即发布', value: 'now' },
      { text: '5分钟后', value: '5min' },
      { text: '30分钟后', value: '30min' },
      { text: '1小时后', value: '1h' },
      { text: '自定义时间', value: 'custom' },
    ];
    const scheduleAction = ref('now');
    const showSchedulePicker = ref(false);
    const scheduleLabel = computed(() => scheduleOptions.find(o => o.value === scheduleAction.value)?.text || '');
    const onScheduleConfirm = (value: any) => {
      const v = Array.isArray(value) ? value[0]?.value : value?.value;
      if (v) scheduleAction.value = v;
      showSchedulePicker.value = false;
    };

    // 获取用户信息（从 localStorage 或默认）
    const userInfo = ref({
      avatar: 'https://via.placeholder.com/50',
      username: '用户名',
    });
    try {
      const stored = localStorage.getItem('userInfo');
      if (stored) Object.assign(userInfo.value, JSON.parse(stored));
    } catch {}

    const publishNote = () => {
      notesStore.addNote({
        content: recordData.value.text.trim(),
        images: recordData.value.photos.map((p: any) => p.url || p.content || p),
        tag: '恋爱',          // 也可做成可选项
        collapsed: false,
        expanded: false,
        data: '2025-09-01 09:18:46'
      });
      router.push({ name: 'notes' }); // 你的路由命名按实际写；之前你用过 '/notes'
    };

    return {
      recordData,
      publishNote,
      // voice
      voiceOptions,
      voiceAction,
      showVoicePicker,
      voiceLabel,
      onVoiceConfirm,
      // AI card
      showAICard,
      aiLoading,
      aiCandidates,
      selectedCandidate,
      regenerateCandidates,
      useSelectedCandidate,
      // permission
      permissionOptions,
      permissionAction,
      showPermissionPicker,
      permissionLabel,
      onPermissionConfirm,
      // schedule
      scheduleOptions,
      scheduleAction,
      showSchedulePicker,
      scheduleLabel,
      onScheduleConfirm,
    };
  },
});
</script>

<style scoped>
.record-editor-view {
  padding: 16px;
  background: #fff;
  min-height: 100vh;
}

.editor-header {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  margin-bottom: 16px;
}

.publish-button {
  color: #fff;
  font-size: 16px;
  padding: 8px 16px;
  border-radius: 4px;
}

.editor-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.editor {
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.editor-textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  font-size: 14px;
  color: #333;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  background: #f9f9f9;
  border-radius: 24px;
}

.toolbar-icon {
  color: #222;
  font-size: 22px;
  margin-right: 18px;
  display: flex;
  align-items: center;
}

.toolbar-icon:last-child {
  margin-right: 0;
}

.toolbar-divider {
  width: 1px;
  height: 24px;
  background: #e5e5e5;
  margin: 0 12px;
}

.toolbar-voice-picker {
  margin-left: auto;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.toolbar-voice-label {
  color: #294c3b;
  font-size: 16px;
  user-select: none;
}

/* === AI 生成卡片 === */
.ai-gen-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.08);
  border: 1px solid #f0f0f0;
  padding: 12px;
}

.ai-gen-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 4px 8px;
}

.ai-gen-title {
  font-size: 15px;
  font-weight: 600;
  color: #ffffff;
}

.ai-gen-actions {
  display: flex;
  gap: 8px;
}

.ai-gen-body {
  padding: 4px;
}

.ai-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 8px;
  color: #666;
}

.ai-candidates {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.ai-candidate {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  border: 2px solid transparent;
  cursor: pointer;
  background: #fafafa;
  transition: transform .1s ease, box-shadow .2s ease, border-color .2s ease;
}

.ai-candidate:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
}

.ai-candidate.selected {
  border-color: #FFD59E;
  box-shadow: 0 0 0 4px #FFF3E0 inset;
}

.ai-candidate img {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
}

.checkmark {
  position: absolute;
  right: 8px;
  top: 8px;
  width: 24px;
  height: 24px;
  background: #F5A623;
  border-radius: 50%;
  display: grid;
  place-items: center;
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}

.ai-gen-footer {
  display: flex;
  justify-content: flex-end;
  padding: 8px 4px 0;
}

.use-button {
  border-radius: 8px;
}

/* === 其它 === */
.settings-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.settings-item {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #294c3b;
  cursor: pointer;
  justify-content: space-between;
  min-height: 40px;
}

.settings-label {
  min-width: 72px;
  text-align: left;
  color: #294c3b;
  font-weight: 500;
  user-select: none;
  margin-right: 8px;
}

.settings-value {
  min-width: 80px;
  text-align: right;
  color: #222;
  font-weight: 400;
  user-select: none;
  margin-right: 0;
}

.settings-divider-solid {
  width: 100%;
  height: 0;
  border-top: 1.5px solid #f0f0f0;
  margin: 0;
  display: block;
}
</style>
